package com.example.back.service.impl;

import com.example.back.dto.req.DepartmentEditReq;
import com.example.back.dto.req.DepartmentListReq;
import com.example.back.dto.resp.HospitalDepartmentResp;
import com.example.back.jpa.DepartmentRository;
import com.example.back.mapper.DepartmentMapper;
import com.example.back.service.DepartmentService;
import com.example.common.entity.HospitalDepartment;
import com.example.common.enums.DepLabel;
import com.example.common.support.ApiException;
import com.example.common.utils.CheckUtils;
import com.example.common.utils.IdUtils;
import com.google.common.collect.Lists;

import org.javers.spring.annotation.JaversAuditable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 科室管理
 */
@Service
public class DepartmentServiceImpl implements DepartmentService {

    @Resource
    private DepartmentRository departmentRository;
    @Resource
    private DepartmentMapper departmentMapper;

    /**
     * 科室列表(获取所有分类)
     * @return
     */
    @Override
    public List<HospitalDepartmentResp> List(DepartmentListReq req){
        List<HospitalDepartmentResp> data = departmentMapper.findByDepartmentLists(req.getName());
        //定义新的list
        List<HospitalDepartmentResp> categoriesList = new ArrayList<>();
        //先找到所有的一级分类
        for(HospitalDepartmentResp category : data){
            category.setLabel(DepLabel.valuesDescription(category.getTypes()));
            // 一级菜单的parentId是0
            if(category.getPdId() == 0){
                category.setPName("/");

                categoriesList.add(category);
            }
        }
        // 为一级菜单设置子菜单，getChild是递归调用的
        for(HospitalDepartmentResp category : categoriesList){
            category.setChildren(getChilde(category.getID(),category.getName(), data));
        }

        return categoriesList;
    }

    /**
     * 递归查找子菜单
     *
     * @param id 当前菜单id
     * @param rootList 要查找的列表
     * @return
     */
    private List<HospitalDepartmentResp> getChilde(Long id, String name, List<HospitalDepartmentResp> rootList){
        //子菜单
        List<HospitalDepartmentResp> childList = new ArrayList<>();
        for(HospitalDepartmentResp category : rootList){
            // 遍历所有节点，将父菜单id与传过来的id比较
            if(category.getPdId().equals(id)){
                category.setPName(name);
                //category.setLabel(DepLabel.valuesDescription(category.getTypes()));
                childList.add(category);
            }
        }
        // 把子菜单的子菜单再循环一遍
        for(HospitalDepartmentResp category : childList){
            category.setChildren(getChilde(category.getID(),name, rootList));
        }
        // 递归退出条件
        if (childList.size() == 0){
            return null;
        }
        return childList;
    }

    /**
     * 启用、禁用
     */
    @Override
    @JaversAuditable
    public Object DoDisable(DepartmentEditReq req) {

        CheckUtils.checkNull(req, new ApiException(10000, "对象不能为空"));

        HospitalDepartment objs = departmentRository.findById(req.getID()).orElse(null);
        if(objs==null){
            throw new ApiException(1, "账号ID不匹配");
        }

        objs.setDisable(!objs.getDisable());
        return departmentRository.save(objs);
    }

    /**
     * 详情
     */
    @Override
    public Object Info(DepartmentEditReq req) {

        HospitalDepartment obj = departmentRository.findById(req.getID()).orElse(null);

        Map<String, Object> mapRow = new HashMap<>();
        if(obj!=null){
            mapRow.put("IsRecommend",obj.getIsRecommend());
            mapRow.put("Label",obj.getLabel());
            mapRow.put("Name",obj.getName());
            mapRow.put("PDID",obj.getPdId());
        }else{
            mapRow=null;
        }


        List list = Lists.newArrayList();

        for (DepLabel e : DepLabel.values()) {

            Map<String, Object> map = new HashMap<>();
            map.put("Value", e.getValue());
            map.put("Description", e.getDescription());
            list.add(map);
        }

        List<HospitalDepartment> hospitalDepartments = departmentRository.findAll();

        List DepartmentList = Lists.newArrayList();

        for (HospitalDepartment hospitalDepartment: hospitalDepartments) {
            Map<String, Object> maplist = new HashMap<>();
            maplist.put("ID",hospitalDepartment.getId());
            maplist.put("Name",hospitalDepartment.getName());
            DepartmentList.add(maplist);
        }

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("info", mapRow);
        hashMap.put("selectLabel", list);
        hashMap.put("selectList", DepartmentList);
        return hashMap;
    }

    /**
     * 保存
     */
    @Override
    @JaversAuditable
    public Object Save(DepartmentEditReq req) {

        CheckUtils.checkNull(req, new ApiException(1, "对象不能为空"));
        HospitalDepartment obj = departmentRository.findById(req.getID()).orElse(null);
        HospitalDepartment objHos = departmentRository.findByName(req.getName());

        if(objHos != null && objHos.getId() != req.getID()){
            throw new ApiException(1,"科室"+req.getName()+"已存在，不能重复");
        }

        if(req.getID() == 0){

            HospitalDepartment hospitalDepartment = new HospitalDepartment();
            hospitalDepartment.setId(IdUtils.generateId());
            hospitalDepartment.setIsRecommend(req.getIsRecommend());
            hospitalDepartment.setCreateTime(new Date());
            hospitalDepartment.setLabel(req.getLabel());
            hospitalDepartment.setPdId(req.getPDID());
            hospitalDepartment.setDisable(false);
            hospitalDepartment.setName(req.getName());

            return departmentRository.save(hospitalDepartment);
        }else{

            if(obj == null){
                throw new ApiException(1, "错误的请求参数");
            }

            obj.setIsRecommend(req.getIsRecommend());
            obj.setLabel(req.getLabel());
            obj.setPdId(req.getPDID());
            obj.setName(req.getName());
            obj.setIsRecommend(req.getIsRecommend());

            return departmentRository.save(obj);
        }
    }
}
